<template>
  <view class="course-page">
    <!-- 导航栏组件 -->
    <NavBar :click="handleGoHome" :title="reportInfo.lessonName"></NavBar>
    <view class="content" :style="getContentStyle()">
      <scroll-view class="content-list" scroll-y="true" :show-scrollbar="false">
        <view class="top">
          <view class="top-content">
            <view class="top-txt-one">{{ getLessonName() }}</view>
            <view class="top-txt-two">{{ reportInfo.finishTime }}</view>
          </view>
          <image class="top-icon" src="/static/images/follow-result-icon.png" mode="scaleToFill"></image>
        </view>
        <view class="card">
          <view class="card-head card-head-column">
            <view class="card-head-title">第{{ reportInfo.exerciseNumber || 1 }}次练习</view>
            <view class="card-head-hint">用时: {{ formatTime(reportInfo.useTime) }}，净语速: {{ reportInfo.wpmAvgVoiced || 0 }}字/分钟</view>
          </view>
          <view class="card-line"></view>
          <!-- 雷达图 -->
          <ChartCircle :progress="reportInfo.comprehensiveScore" />
          <view class="info-box">
            <view class="info-item">
              <text class="info-item-one">历史最高分</text>
              <text class="info-item-two">{{ reportInfo.maxScore || 0 }}</text>
            </view>
            <view class="info-empty"></view>
            <view class="info-item">
              <text class="info-item-one">历史平均分</text>
              <text class="info-item-two">{{ reportInfo.avgScore || 0 }}</text>
            </view>
            <view class="info-empty"></view>
            <view class="info-item">
              <text class="info-item-one">练习及格分</text>
              <text class="info-item-two">{{ reportInfo.passingScore || 0 }}</text>
            </view>
          </view>
          <view class="card-line" style="margin-bottom: 0px;"></view>
          <!-- 雷达图 -->
          <ChartRadar 
            style="padding-bottom: 16px;"
            :exerciseType="reportInfo.exerciseType"
            :completeness="Number(reportInfo.completeness) || 0"
            :accuracy="Number(reportInfo.fillWordsStuttering) || 0"
            :fluency="Number(reportInfo.fluency) || 0"
            :confidence="Number(reportInfo.confidence) || 0"
            :speedVolume="Number(reportInfo.speedVolume) || 0"
            :readabilityScore="Number(reportInfo.readabilityScore) || 0"
          />
        </view>
        <view class="card">
          <view class="card-head">
            <text class="card-head-title">本次详细分析</text>
            <image @click="handleShowMore" class="card-head-icon" :src="showMore ? '/static/images/arrow-up-black.png' : '/static/images/arrow-down-black.png'" mode="scaleToFill"></image>
          </view>
          <template v-if="showMore">
            <view class="card-line"></view>
            <view v-for="(item, index) in reportCardList" :key="index" class="info-card">
              <view class="info-card-top">
                <view class="info-card-top-title">{{ item.title }}</view>
                <view class="progress-tag" :class="item.tagClass">{{ item.tag }}</view>
                <view class="info-card-top-empty"></view>
                <view class="progress-bar">
                  <view class="progress-fill" :style="{ width: item.progress + '%', background: item.progressColor }"></view>
                </view>
                <view class="progress-number">{{ item.progress }}</view>
              </view>
              <view class="info-card-content">{{ item.content }}</view>
            </view>
          </template>
        </view>
        <view class="card">
          <view class="card-head">
            <text class="card-head-title">历史趋势分析</text>
          </view>
          <view class="card-line"></view>
          <!-- 折线图 -->
          <ChartLine :dataList="reportInfo.exerciseList" />
        </view>
        <view class="hint-txt">希望本报告对您的成长有所帮助！</view>
        <view class="hint-txt">请继续保持优势，并在薄弱环节多加练习。</view>
        <view class="video-box">
          <video v-if="!showImage" id="myVideo" class="video-element" @fullscreenchange="handleFullscreen" :src="videoUrl" @error="videoErrorCallback" @play="videoPlayCallback" @ended="videoEndedCallback" :show-fullscreen-btn="false" :controls="true"></video>
          <image v-show="showImage" class="video-icon" :src="videoPoster" mode="aspectFit"></image>
          <view v-show="showImage" class="video-btn" @click="handlePreviewVideo">
            <image class="video-btn-icon" src="/static/images/start-icon.png" mode="scaleToFill"></image>
            <text class="video-btn-txt">播放</text>
          </view>
          <view class="video-hint">注意：视频仅保存3天</view>
        </view>
      </scroll-view>
      <view class="bottom-box">
        <view class="bottom-btn" @click="handleGoLean()">再练一次</view>
      </view>
    </view>
  </view>
</template>

<script >
import ChartCircle from './chartCircle.vue'
import ChartRadar from './chartRadar.vue'
import ChartLine from './chartLine.vue'
import { getReport, getLesson } from '@/api/course.js'
import { RESOURCE_URL } from '@/api/request.js'
import { formatTime as formatTimeUtil } from '@/utils/index.js'

export default {
  components: {
    ChartCircle,
    ChartRadar,
    ChartLine
  },
  data() {
    return {
      showMore: true,
      showImage: true,
      exerciseId: '',
      videoPoster: '',
      videoUrl: '',
      reportInfo: {
        exerciseList: []
      },
      questionsMap: {
        F: '这个产品有什么特征？',
        A: '相对竞争对手有什么优势？',
        B: '这些优势能给客户带来什么好处？',
        E: '有什么证据支撑？如数据、案例、认证等',
      },
      questionsTagMap: {
        F: '特征',
        A: '优势',
        B: '利益',
        E: '证据',
      },
    }
  },
  onLoad(options) {
    this.exerciseId = options.exerciseId
    this.getReportInfo()
  },
  computed: {
    reportCardList() {
      const cardList = [
        {
          title: '完整度',
          tag: '优秀',
          tagClass: '',
          progress: Number(this.reportInfo.completeness) || 0,
          progressColor: '#2AB55E',
          content:  this.reportInfo.completenessMessage || '',
        },
        {
          title: '准确度',
          tag: '优秀',
          tagClass: '',
          progress: Number(this.reportInfo.fillWordsStuttering) || 0,
          progressColor: '#2AB55E',
          content: this.reportInfo.accuracyMessage || '',
        },
        {
          title: '流畅度',
          tag: '优秀',
          tagClass: '',
          progress: Number(this.reportInfo.fluency) || 0,
          progressColor: '#2AB55E',
          content: this.reportInfo.fluencyMessage || '',
        },
        {
          title: '自信度',
          tag: '优秀',
          tagClass: '',
          progress: Number(this.reportInfo.confidence) || 0,
          progressColor: '#2AB55E',
          content: this.reportInfo.confidenceMessage || '',
        },
        {
          title: '语速音量',
          tag: '优秀',
          tagClass: '',
          progress: Number(this.reportInfo.speedVolume) || 0,
          progressColor: '#2AB55E',
          content: this.reportInfo.speedVolumeMessage || '',
        }
      ]
      if (this.reportInfo.exerciseType === 102) {
        cardList.push({
          title: '语速音量',
          tag: '优秀',
          tagClass: '',
          progress: Number(this.reportInfo.speedVolume) || 0,
          progressColor: '#2AB55E',
          content: this.reportInfo.speedVolumeMessage || '',
        })
      } else if (this.reportInfo.exerciseType === 103) {
        cardList.push({
          title: '通俗度',
          tag: '优秀',
          tagClass: '',
          progress: Number(this.reportInfo.readabilityScore) || 0,
          progressColor: '#2AB55E',
          content: this.reportInfo.readabilityScoreDesc || '',
        })
      }
      const rangeInfo = {
        1: { tagClass: 'progress-tag-red', tag: '需改进', progressColor: '#F02525' },
        2: { tagClass: 'progress-tag-yellow', tag: '一般', progressColor: '#F28F15' },
        3: { tagClass: 'progress-tag-blue', tag: '良好', progressColor: '#315BF4' },
        4: { tagClass: '', tag: '优秀', progressColor: '#2AB55E' },
        5: { tagClass: '', tag: '卓越', progressColor: '#2AB55E' }
      }
      cardList.forEach(item => {
        let progress = 1
        if (item.progress <= 59) {
          progress = 1
        } else if (item.progress >= 59 && item.progress <= 69) {
          progress = 2
        } else if (item.progress >= 69 && item.progress <= 85) {
          progress = 3
        } else if (item.progress >= 85 && item.progress <= 95) {
          progress = 4
        } else if (item.progress >= 95 && item.progress <= 100) {
          progress = 5
        }
        item.tagClass = rangeInfo[progress].tagClass
        item.tag = rangeInfo[progress].tag
        item.progressColor = rangeInfo[progress].progressColor
      })
      return cardList
    },
    exerciseMaxScore() {
      if (this.reportInfo && this.reportInfo.exerciseList && this.reportInfo.exerciseList.length) {
        // 返回comprehensiveScore最大值
        const scores = this.reportInfo.exerciseList.map(item => item.comprehensiveScore || 0)
        return Math.max(scores)
      }
      return 0
    },
    exerciseAverageScore() {
      if (this.reportInfo && this.reportInfo.exerciseList && this.reportInfo.exerciseList.length) {
        // 返回comprehensiveScore平均值
        const scores = this.reportInfo.exerciseList.map(item => item.comprehensiveScore || 0)
        const sum = scores.reduce((acc, cur) => acc + cur, 0)
        return Math.round(sum / scores.length)
      }
      return 0
    }
  },
  methods: {
    getLessonName() {
      if (this.reportInfo.exerciseType === 102) {
        return '话术跟读'
      } else if (this.reportInfo.exerciseType === 103) {
        return '脱稿演练'
      } else if (this.reportInfo.exerciseType === 104) {
        return '模拟对话'
      } else {
        return this.reportInfo.lessonName
      }
    },
    handleGoHome() {
      // 默认返回上一页
      uni.navigateBack({
        fail: () => {
          // 如果没有上一页，则跳转到首页
          uni.switchTab({
            url: '/pages/index/home'
          })
        }
      })
    },
    async handleGoLean() {
      let questions = []
      if (this.reportInfo.exerciseType === 102) {
        // 话术跟读获取跟读内容
        const info= await getLesson(this.reportInfo.courseId, this.reportInfo.lessonId)
        Object.keys(this.questionsMap).map((key) => {
          if (info.salesLanguageMap[key]) {
            questions.push({
              key,
              question: this.questionsMap[key],
              tag: this.questionsTagMap[key],
              response: info.salesLanguageMap[key]
            })
          }
        })
      }
      const pageData = {
        questions: questions,
        courseId: this.reportInfo.courseId,
        lessonId: this.reportInfo.lessonId,
        exerciseType: this.reportInfo.exerciseType
      }
      const json = JSON.stringify(pageData)
      uni.redirectTo({
        url: `/pages/course/follow/index?l=${json}`
      })
    },
    async getReportInfo() {
      const result = await getReport(this.exerciseId)
      this.reportInfo = result
      this.videoPoster = ''
      this.videoUrl = ''
      if (this.reportInfo?.exerciseFiles) {
        this.reportInfo.exerciseFiles.forEach(it => {
          if (it.isPicture === 1 || it.isPicture === '1') {
            this.videoPoster = RESOURCE_URL + it.filePath
            console.log('videoPoster', this.videoPoster)
          }
          if (it.fileName.includes('.mp4')) {
            this.videoUrl = RESOURCE_URL + it.filePath
          }
        })
        console.log('----1', this.videoPoster)
        console.log('----2', this.videoUrl)
      }
    },
    getContentStyle() {
      const statusBarHeight = uni.getSystemInfoSync().statusBarHeight || 0
      return {
        height: `calc(100% - ${(statusBarHeight + 44)}px)`
      }
    },
    handlePreviewVideo() {
      this.showImage = false
      this.$nextTick(() => {
        const videoContext = uni.createVideoContext('myVideo')
        videoContext.play()
        videoContext.requestFullScreen()
      })
    },
    handleShowMore() {
      this.showMore = !this.showMore
    },
    handleFullscreen(event) {
      console.log('event.detail.fullScreen', event.detail.fullScreen)
      if (!event.detail.fullScreen) {
        this.videoEndedCallback()
      }
    },
    videoEndedCallback() {
      console.log('--videoEndedCallback')
      this.showImage = true
      const videoContext = uni.createVideoContext('myVideo')
      videoContext.exitFullScreen()
    },
    videoPlayCallback() {
      // 开始播放
      this.showImage = false
    },
    videoErrorCallback() {
      uni.showToast({
        title: '播放失败'
      })
    },
    formatTime(seconds) {
      return formatTimeUtil(seconds)
    }
  }
}
</script>

<style lang="scss">
.course-page {
  width: 100%;
  height: 100vh;
  background: linear-gradient(191deg, #DCECFF 0%, #F6F7FB 100%);
}

.content {
  width: 100%;
  padding: 32rpx;
  padding-bottom: 144rpx;
  display: flex;
  flex-direction: column;
  .content-list{
    width: 100%;
    height: calc(100% - 32rpx);
    padding-bottom: 32rpx;
  }
}
.top{
  width: 100%;
  height: 192rpx;
  padding: 0 32rpx;
  display: flex;
  flex-direction: row;
  overflow: hidden;
  .top-content{
    flex: 1;
    margin: 0 32rpx;
    margin-top: 48rpx;
    .top-txt-one{
      color: #202844;
      font-size: 48rpx;
      font-weight: 600;
      line-height: 64rpx;
      letter-spacing: 0px;
    }
    .top-txt-two{
      font-size: 24rpx;
      color: rgba(32, 40, 68, 0.65);
      line-height: 40rpx;
      margin-top: 8rpx;
    }
  }
  .top-icon{
    width: 236rpx;
    height: 240rpx;
    margin-right: 16rpx;
  }
}

.card{
  width: 100%;
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 0 48rpx;
  margin-bottom: 32rpx;
  display: flex;
  flex-direction: column;
  .card-head{
    width: 100%;
    min-height: 110rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    .card-head-title{
      color: #333333;
      font-size: 32rpx;
      line-height: 48rpx;
      font-weight: 600;
      flex: 1;
    }
    .card-head-icon{
      width: 48rpx;
      height: 48rpx;
    }
  }
  .card-head-column{
    flex-direction: column;
    align-items: start;
    .card-head-title{
      flex: none;
      margin-bottom: 8rpx;
      margin-top: 32rpx;
    }
    .card-head-hint{
      font-size: 28rpx;
      line-height: 44rpx;
      color: #999999;
      margin-bottom: 32rpx;
    }
  }
  .card-line{
    width: 100%;
    border-top: 2rpx solid #EBEDEF;
    margin-bottom: 32rpx;
  }
}
.info-box{
  width: 100%;
  display: flex;
  flex-direction: row;
  margin-top: 32rpx;
  .info-empty{
    flex: 1;
  }
  .info-item{
    display: flex;
    flex-direction: column;
    margin-bottom: 32rpx;
    .info-item-one{
      color: #666666;
      font-size: 28rpx;
      line-height: 44rpx;
    }
    .info-item-two{
      color: #1F1F1F;
      font-size: 40rpx;
      line-height: 56rpx;
    }
  }
}
.info-card{
  width: 100%;
  display: flex;
  flex-direction: column;
  background: #FAFAFA;
  padding: 16rpx;
  margin-bottom: 32rpx;
  border-radius: 16rpx;
  .info-card-top{
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 16rpx;
    .info-card-top-title{
      color: #333333;
      font-size: 28rpx;
      font-weight: 600;
      line-height: 44rpx;
    }
    .info-card-top-empty{
      flex: 1;
    }
    .progress-number{
      color: #1F1F1F;
      line-height: 44rpx;
      font-size: 28rpx;
      width: 54rpx;
      text-align: right;
    }
    .progress-bar{
      width: 196rpx;
      height: 8rpx;
      border-radius: 1200rpx;
      background: #F2F4F6;
      margin-right: 16rpx;
      position: relative;
      .progress-fill{
        height: 8rpx;
        border-radius: 1200rpx;
        position: absolute;
        right: 0;
        top: 0;
      }
    }
    .progress-tag{
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      padding: 0rpx 8rpx;
      border-radius: 4rpx;
      background: #E9F7EE;
      color: #2AB55E;
      font-size: 24rpx;
      line-height: 40rpx;
      margin-left: 16rpx;
    }
    .progress-tag-red{
      color: #F02525;
      background: #FFF2F0;
    }
    .progress-tag-yellow{
      color: #F28F15;
      background: #FFF8E6;
    }
    .progress-tag-blue{
      color: #155BD4;
      background: #E6F3FF;
    }
  }
  .info-card-content{
    color: #666666;
    font-size: 24rpx;
    line-height: 40rpx;
  }
}
.hint-txt{
  color: #999999;
  font-size: 28rpx;
  line-height: 44rpx;
  width: 100%;
  text-align: center;
}
.bottom-box{
  width: 100%;
  height: 144rpx;
  padding: 0 32rpx;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  position: fixed;
  left: 0;
  bottom: 0;
  background: white;
  .bottom-btn{
    width: 100%;
    height: 96rpx;
    border-radius: 24rpx;
    background: #FFFFFF;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    background: linear-gradient(270deg, #4677F4 0%, #7FA2FC 100%);
    font-size: 32rpx;
    font-weight: 600;
    color: #FFFFFF;
  }
}
.video-box{
  width: 100%;
  height: 568rpx;
  border-radius: 24rpx;
  overflow: hidden;
  position: relative;
  background: #FFFFFF;
  margin: 32rpx 0;
  font-size: 0;
  .video-element{
    width: 100%;
    height: 496rpx;
    border-radius: 16rpx 16rpx 0 0;
  }
  .video-icon{
    width: 100%;
    height: 496rpx;
    background: black;
    border-radius: 16rpx 16rpx 0 0;
    position: absolute;
    top: 0;
    left: 0;
  }
  .video-hint{
    width: 100%;
    height: 72rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #EE8049;
    font-size: 24rpx;
    position: absolute;
    bottom: 0;
  }
  .video-btn{
    width: 160rpx;
    height: 76rpx;
    border-radius: 16rpx;
    background: rgba(0, 0, 0, 0.6);
    position: absolute;
    left: 50%;
    top: 230rpx;
    transform: translateX(-50%);
    display: flex;
    align-items: center;
    justify-content: center;
    .video-btn-icon{
      width: 32rpx;
      height: 32rpx;
      margin-right: 8rpx;
    }
    .video-btn-txt{
      color: #FFFFFF;
      font-size: 28rpx;
      line-height: 44rpx;
    }
    .video-btn-txt{
      color: rgba(255, 255, 255, 0.95);
      font-size: 28rpx;
    }
  }
}
</style>
